package com.uh.microservice.core.spring.bean;

import com.uh.microservice.core.spring.SpringUtil;
import com.uh.microservice.core.util.CacheUtil;
import com.uh.microservice.core.util.LogUtil;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;

/**
 * 缓存的切面类
 * Created by liming on 2017/10/10.
 */
@Aspect
@Configuration
public class CacheAspect {

    private LogUtil logger = new LogUtil(this.getClass());
    /**
     *  入口配置
     */
    @Pointcut("execution(* com.uh.microservice.core.service.CacheService.find*(..))")
    public void excudeService(){}

    /**
     *  具体的切面方法
     */
    @Around("excudeService()")
    public Object cacheAsOld(ProceedingJoinPoint point){
        Object thing=null;
        try {
            point.getArgs();
            MethodSignature signature = (MethodSignature)point.getSignature();
            Method method = signature.getMethod();
            String methodName = method.getName();
            String key = addNameSpace(methodName);
            for (Object value : point.getArgs()) {

                if(value instanceof ScriptObjectMirror){

                    Set<Map.Entry<String,Object>> entrys = ((ScriptObjectMirror) value).entrySet();

                    for(Map.Entry item : entrys){
                        key +=  "_" + item.getValue();
                    }
                }else{

                    key +=  "_" + value;
                }
            }

            if(SpringUtil.isDebug()){
                thing = point.proceed();
            }else {
                try {
                    thing = CacheUtil.instance().getKey(key);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (thing == null) {
                    thing = point.proceed();
                    if(key!=null && StringUtils.isEmpty(key))
                        CacheUtil.instance().putKey(key, thing);
                }
            }

            return thing;
        } catch (Throwable e) {
            e.printStackTrace ();
        }
        return thing;
    }

    /**
     * 为缓存 添加特定的前缀 方便缓存管理
     * @param methodName
     * @return
     */
    private String addNameSpace(String methodName) {

        switch (methodName){
            case "findBillRateCollection":
                return CacheUtil.CACHE_NAME_SPACE_RATE_CACHE + methodName;
            case "findSysParams":
                return CacheUtil.CACHE_NAME_SPACE_SYS_PARAM + methodName;
        }
        return methodName;
    }

}
